#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.Net;
using System.Text.RegularExpressions;
using CchenSoft.Portal.Web;

namespace CchenSoft.Portal.Blog.Tracking
{
	/// <summary>
	/// Used to verify that a trackback or pingback source actually contains a link to this site.
	/// </summary>
	public static class Verifier
	{
		/// <summary>
		/// Checks that the contents of the source url contains the target URL.
		/// </summary>
		/// <param name="sourceUrl">The source URL.</param>
		/// <param name="targetUrl">The target URL.</param>
		/// <param name="pageTitle">The page title.</param>
		/// <returns></returns>
		public static bool SourceContainsTarget(Uri sourceUrl, Uri targetUrl, out string pageTitle)
		{
			pageTitle = string.Empty;
			string page = null;
			try
			{
				page = HttpHelper.GetPageText(sourceUrl);
			}
			catch(WebException e)
			{
				//Log.Warn("Could not verify the source of a ping/trackback", e);
			}
			if (page == null || targetUrl == null)
				return false;
					
			string pat = @"<head.*?>.*<title.*?>(.*)</title.*?>.*</head.*?>" ;
			Regex reg = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.Singleline) ;
			Match m = reg.Match(page) ;
			if(m.Success)
			{
				pageTitle = m.Result("$1") ;
				return true;
			}
			return false;
		}
		
		/// <summary>
		/// Checks that the contents of the source url contains the target URL.
		/// </summary>
		/// <param name="sourceUrl">The source URL.</param>
		/// <param name="targetUrl">The target URL.</param>
		/// <returns></returns>
		public static bool SourceContainsTarget(Uri sourceUrl, Uri targetUrl)
		{
			string page;
			return SourceContainsTarget(sourceUrl, targetUrl, out page);
		}
	}
}

